#coding:utf-8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

#配置
class Config(object):
    # mysql连接
    SQLALCHEMY_DATABASE_URI = "mysql://root:mysql@127.0.0.1:3306/flask_test"
    # 追踪
    SQLALCHEMY_TRACK_MODIFICATIONS = True

    # SECRET_KEY = 'ADFJL;KJIQEUW89-FAED'

app.config.from_object(Config)


# 操作数据库db
db = SQLAlchemy(app)


#创建作者表
class Author(db.Model):
    #定义表名
    __tablename__ = 'tbl_authors'


    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)

    #外键反推
    books = db.relationship('Book', backref='author')


#创建书籍表
class Book(db.Model):
    __tablename__ = 'tbl_books'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    #设置外键
    author_id = db.Column(db.Integer, db.ForeignKey('tbl_authors.id'))


if __name__ == '__main__':
    #第一次创建表的时候,先清除数据
    db.drop_all()
    #创建表
    db.create_all()

    # #向author表添加内容
    au_zhang = Author(name='张三')
    au_li = Author(name='李四')
    au_wang = Author(name='王二')
    db.session.add_all([au_li,au_wang,au_zhang])
    db.session.commit()


    #向Book表添加内容
    bk_zhang = Book(name='西游记', author_id=au_zhang.id)
    bk_zhang2 = Book(name='西游', author_id = au_zhang.id)
    bk_zhang3 = Book(name='红楼', author_id = au_li.id)
    bk_zhang4 = Book(name='红楼梦', author_id = au_li.id)
    bk_zhang5 = Book(name='三国', author_id = au_wang.id)
    bk_zhang6 = Book(name='三国演绎', author_id = au_wang.id)
    db.session.add_all([bk_zhang,bk_zhang2,bk_zhang3,bk_zhang4,bk_zhang5,bk_zhang6])
    db.session.commit()




    # app.run(debug=True)